package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.TRegisterDept;
import com.ruoyi.business.domain.TRegisterNeed;
import com.ruoyi.business.mapper.TRegisterNeedMapper;
import com.ruoyi.business.service.ITRegisterDconfigService;
import com.ruoyi.business.service.ITRegisterDeptService;
import com.ruoyi.business.service.ITRegisterNeedService;
import com.ruoyi.business.vo.TRegisterDconfigVo;
import com.ruoyi.business.vo.TRegisterNeedVo;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 招生信息Service业务层处理
 *
 * @author Tellsea
 * @date 2024-01-17
 */
@Service
@RequiredArgsConstructor
public class TRegisterNeedServiceImpl extends ServiceImpl<TRegisterNeedMapper, TRegisterNeed> implements ITRegisterNeedService {

    private final ITRegisterDeptService registerDeptService;

    private final ITRegisterDconfigService registerDconfigService;


    private void handleAuth(TRegisterNeedVo entity) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        if (SecurityUtils.hasRole(RoleConstants.SECRETARY.getRoleKey())
                || SecurityUtils.hasRole(RoleConstants.DEPT_MANAGE.getRoleKey())) {
            List<TRegisterDept> deptList = registerDeptService.lambdaQuery()
                    .eq(TRegisterDept::getManageUserId, userId)
                    .or()
                    .eq(TRegisterDept::getSecretaryUserId, userId)
                    .list();
            entity.setRegisterDeptIdList(deptList.stream().map(TRegisterDept::getId).collect(Collectors.toList()));
        }
    }

    @Override
    public TableDataInfo<TRegisterNeedVo> queryList(TRegisterNeedVo entity) {
        handleAuth(entity);

        Page<TRegisterNeedVo> needVoPage = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        List<TRegisterNeedVo> records = needVoPage.getRecords();

        handleDconfigMapping(records);

        return PageUtils.buildDataInfo(needVoPage);
    }

    @Override
    public List<TRegisterNeedVo> queryAll(TRegisterNeedVo entity) {
        handleAuth(entity);
        List<TRegisterNeedVo> needVos = this.baseMapper.queryList(entity);
        handleDconfigMapping(needVos);
        return needVos;
    }

    @Override
    public List<TRegisterNeedVo> queryAllOri(TRegisterNeedVo entity) {
        handleAuth(entity);
        return this.baseMapper.queryList(entity);
    }

    @Override
    public TRegisterNeedVo queryById(Long id) {
        // 构建缓存：查询所有【关闭状态】的数据（这些项需要被删除）
        TRegisterDconfigVo dconfigQuery = new TRegisterDconfigVo();
        List<TRegisterDconfigVo> dconfigVoList = registerDconfigService.queryAll(dconfigQuery);

        Map<String,String> dConfigCache = new HashMap<>();
        Set<String> closedConfigCache = new HashSet<>();
        for (TRegisterDconfigVo config : dconfigVoList) {
            if (StringUtils.isNotEmpty(config.getRegisterYear())
                    && StringUtils.isNotEmpty(config.getRegisterMonth())) {
                dConfigCache.put(config.getRegisterMonth(),config.getRegisterYear());
                if(config.getRegisterStatus()!=null && config.getRegisterStatus()==0){
                    closedConfigCache.add(config.getRegisterMonth());
                }
            }
        }
        TRegisterNeedVo needVo = this.baseMapper.queryById(id);
        if(needVo!=null){
            handleDconfigItem(needVo, dConfigCache, closedConfigCache);
        }
        return needVo;
    }

    /**
     * 已开启数据映射配置
     * @param records 查询记录
     */
    private void handleDconfigMapping(List<TRegisterNeedVo> records) {
        // 构建缓存：查询所有【关闭状态】的数据（这些项需要被删除）
        TRegisterDconfigVo dconfigQuery = new TRegisterDconfigVo();
        List<TRegisterDconfigVo> dconfigVoList = registerDconfigService.queryAll(dconfigQuery);

        Map<String,String> dConfigCache = new HashMap<>();
        Set<String> closedConfigCache = new HashSet<>();
        for (TRegisterDconfigVo config : dconfigVoList) {
            if (StringUtils.isNotEmpty(config.getRegisterYear())
                    && StringUtils.isNotEmpty(config.getRegisterMonth())) {
                dConfigCache.put(config.getRegisterMonth(),config.getRegisterYear());
                if(config.getRegisterStatus()!=null && config.getRegisterStatus()==0){
                    closedConfigCache.add(config.getRegisterMonth());
                }
            }
        }
        for (TRegisterNeedVo recordItem : records) {
            handleDconfigItem(recordItem, dConfigCache, closedConfigCache);
        }
    }

    private void handleDconfigItem(TRegisterNeedVo needVo, Map<String,String> dConfigCache,Set<String> closedConfigCache) {
        String batchNameList = needVo.getBatchNameList();
        String batchDateList = needVo.getBatchDateList();

        // 仅当核心字段非空时才处理（避免空指针）
        if (StringUtils.isNotEmpty(batchNameList) && StringUtils.isNotEmpty(batchDateList)) {
            // 拆分原始数据数组（优先保留原数据结构）
            String[] batchNames = batchNameList.split(",");
            String[] batchDates = batchDateList.split(",");
            // 1. 确定需要删除的索引（存在于关闭配置缓存中的项）
            Set<Integer> deleteIndexes = new HashSet<>();
            // 取最小长度避免数组越界（以核心字段为准）
            int validLength = Math.min(batchNames.length, batchDates.length);

            for (int i = 0; i < validLength; i++) {
                // 若当前项在【关闭配置缓存】中，标记为删除
                if (closedConfigCache.contains(batchNames[i].trim())) {
                    deleteIndexes.add(i);
                }
            }

            // 2. 保留未被标记删除的项（优先保留原数据）
            List<String> retainedBatchNames = new ArrayList<>(validLength);
            List<String> retainedBatchDates = new ArrayList<>(validLength);
            List<String> needNames = new ArrayList<>(validLength);
            for (int i = 0; i < validLength; i++) {
                if (!deleteIndexes.contains(i)) { // 仅保留未被标记删除的项
                    retainedBatchNames.add(batchNames[i].trim());
                    retainedBatchDates.add(batchDates[i]);
                    needNames.add(dConfigCache.get(batchNames[i].trim()));
                }
            }

            // 3. 重新拼接并赋值过滤后的数据（空集合会被拼接为""，避免null）
            needVo.setBatchNameList(StringUtils.join(retainedBatchNames, ","));
            needVo.setBatchDateList(StringUtils.join(retainedBatchDates, ","));
            needVo.setNeedNameList(StringUtils.join(needNames, ","));
        }
    }

}
